package com.example.petchating.entities

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Animation
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Rectangle
import com.example.petchating.UI.ButtonGroup
import com.example.petchating.collision.CollisionManager
import ktx.assets.disposeSafely


// 单例模式管理资源
object ResourceManager {
    // 加载行走动画图集
    // 单例类在整个程序运行期间只会有一个实例，并且这个实例会在属性在第一次被访问时才会进行初始化并创建
    val downAtlas: TextureAtlas by lazy { TextureAtlas(Gdx.files.internal("Characters/walk/walk_down.atlas")) }
    val upAtlas: TextureAtlas by lazy { TextureAtlas(Gdx.files.internal("Characters/walk/walk_up.atlas")) }
    val leftAtlas: TextureAtlas by lazy { TextureAtlas(Gdx.files.internal("Characters/walk/walk_left.atlas")) }
    val rightAtlas: TextureAtlas by lazy { TextureAtlas(Gdx.files.internal("Characters/walk/walk_right.atlas")) }

    fun dispose() {
        downAtlas.disposeSafely()
        upAtlas.disposeSafely()
        leftAtlas.disposeSafely()
        rightAtlas.disposeSafely()
    }
}

class Pet(
    //人物初始位置，相对游戏世界坐标，原点在左下角
    private var x : Float = 100f,
    private var y : Float = 200f,
    //人物大小
    private val size : Float = 16f
) {
    //移动速度
    private val speed = 50f // 像素/秒

    private val sprite: Sprite
    private val walkingDownAnimation: Animation<TextureRegion>
    private val walkingUpAnimation: Animation<TextureRegion>
    private val walkingLeftAnimation: Animation<TextureRegion>
    private val walkingRightAnimation: Animation<TextureRegion>
    private var stateTime: Float = 0f // 动画时间，用于切换动画帧

    private var currentAnimation: Animation<TextureRegion>? = null
    enum class Direction {
        UP, DOWN, LEFT, RIGHT
    }
    //移动停止前最后指向的方向
    private var lastDirection: Direction = Direction.DOWN
    private val staticFrames : Map<Pet. Direction, TextureRegion>

    //心情值，初始为60
    var mood: Int = 60
        private set

    // 碰撞管理器引用
    private lateinit var collisionManager: CollisionManager

    // 用于碰撞检测的矩形
    val collisionBounds = Rectangle()

    init {
        // 使用单例管理的图集
        val walkDownFrames = ResourceManager.downAtlas.regions
        val walkUpFrames = ResourceManager.upAtlas.regions
        val walkLeftFrames = ResourceManager.leftAtlas.regions
        val walkRightFrames = ResourceManager.rightAtlas.regions
        // 为每个方向创建动画
        walkingDownAnimation = Animation(.1f, walkDownFrames, Animation.PlayMode.LOOP)
        walkingUpAnimation = Animation(.1f, walkUpFrames, Animation.PlayMode.LOOP)
        walkingLeftAnimation = Animation(.1f, walkLeftFrames, Animation.PlayMode.LOOP)
        walkingRightAnimation = Animation(.1f, walkRightFrames, Animation.PlayMode.LOOP)
        //缓存每个方向上的最后一帧
        staticFrames = mapOf(
            Direction.UP to walkingUpAnimation.getKeyFrames().first(),
            Direction.DOWN to walkingDownAnimation.getKeyFrames().first(),
            Direction.LEFT to walkingLeftAnimation.getKeyFrames().first(),
            Direction.RIGHT to walkingRightAnimation.getKeyFrames().first(),
        )
        // 加载角色初始/静止图像（main.png）
        val staticTexture = Texture(Gdx.files.internal("Characters/main.png"))
        sprite = Sprite(staticTexture)
        sprite.setSize(size, size) // 设置角色图块大小
        sprite.setPosition(x, y)

        // 初始化碰撞块，与角色图块大小相同
        collisionBounds.setSize(size, size)
        collisionBounds.setPosition(x, y)
    }


    //匹配方向按钮更新动画帧和移动位置
    fun updatePetMove(buttonGroup: ButtonGroup, delta: Float) {
        var dx = 0f
        var dy = 0f
        if(buttonGroup.buttons[0].isPressed) {
            currentAnimation = walkingUpAnimation
            lastDirection = Direction.UP
            dy += speed * delta
        }
        else if(buttonGroup.buttons[1].isPressed) {
            currentAnimation = walkingDownAnimation
            lastDirection = Direction.DOWN
            dy -= speed * delta
        }
        else if(buttonGroup.buttons[2].isPressed) {
            currentAnimation = walkingLeftAnimation
            lastDirection = Direction.LEFT
            dx -= speed * delta
        }
        else if(buttonGroup.buttons[3].isPressed){
            currentAnimation = walkingRightAnimation
            lastDirection = Direction.RIGHT
            dx += speed * delta
        }
        else{
            currentAnimation = null
        }
        move(dx,dy)
        //更新动画时间
        stateTime += delta
    }

    // 设置碰撞管理器
    fun setCollisionManager(manager: CollisionManager) {
        this.collisionManager = manager
    }

    //检测碰撞并移动位置
    private fun move(dx: Float, dy: Float) {
        val newX = x + dx
        val newY = y + dy
        // 移动时检查碰撞,如果发生碰撞则不移动位置
        if (!(dy==0f&&dx==0f)&&!collisionManager.checkCollision(newX, newY, collisionBounds)) {
            x = newX
            y = newY
        }
        // 更新碰撞块位置
        collisionBounds.setPosition(x , y)
    }

    fun draw(batch: SpriteBatch) {
        val currentFrame: TextureRegion = if (currentAnimation != null) {
            currentAnimation!!.getKeyFrame(stateTime)
        } else {
            staticFrames[lastDirection] ?: walkingDownAnimation.getKeyFrames().first()
        }
        sprite.setRegion(currentFrame)
        sprite.setPosition(x, y)
        sprite.draw(batch)

        // 显示心情值
        val font = BitmapFont() // 使用默认字体
        font.draw(batch, "$mood", x, y + sprite.height + 10) // 在角色上方显示心情值
    }

    // 更新心情值
    fun updateMood(emotion: String) {
        mood = when (emotion) {
            "积极" -> mood + 5
            "消极" -> mood - 5
            else -> mood
        }
        // 限制心情值在0到100之间
        mood = mood.coerceIn(0, 100)
    }

    //  获取角色中心位置
    fun getX() = x + sprite.width / 2
    fun getY() = y + sprite.height / 2

    fun dispose() {
        sprite.texture.dispose()
        ResourceManager.dispose()
    }

    //角色静止和行走时的动画帧状态切换逻辑
//    fun update(delta: Float) {
//        var dx = 0f
//        var dy = 0f

//        // 判断按键方向并更新动画
//        if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
//            dx -= speed * delta
//            currentAnimation = walkingLeftAnimation
//            lastDirection = Direction.LEFT
//        }
//        if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
//            dx += speed * delta
//            currentAnimation = walkingRightAnimation
//            lastDirection = Direction.RIGHT
//        }
//        if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
//            dy += speed * delta
//            currentAnimation = walkingUpAnimation
//            lastDirection = Direction.UP
//        }
//        if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
//            dy -= speed * delta
//            currentAnimation = walkingDownAnimation
//            lastDirection = Direction.DOWN
//        }

//        // 如果没有按下方向键，保持静止状态（使用main.png）
//        if (!Gdx.input.isKeyPressed(Input.Keys.LEFT) &&
//            !Gdx.input.isKeyPressed(Input.Keys.RIGHT) &&
//            !Gdx.input.isKeyPressed(Input.Keys.UP) &&
//            !Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
//
//            currentAnimation = null // 禁用动画
//        }
//
//        // 更新位置
//        x += dx
//        y += dy
//        更新动画时间
//        stateTime += delta
//    }
}
